# !/usr/bin/env python
# -*- coding: utf-8 -*-
from pprint import pprint

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from mytest import models
from mytest.utils.common_crud import ComCrud
from mytest.utils.forms import PrettyNumModelForm


def pretty_list(request):
    """ 靓号列表 """

    # 1. 查询关键字处理
    search = {}
    keyword = request.GET.get('keyword', "")

    if keyword:
        search = {
            "mobile__contains": keyword
        }

    from mytest.utils.pagination import Pagination

    queryset = models.PrettyNum.objects.all().order_by('-id').filter(**search)

    # print(queryset.values())

    # 分页的请求参数
    parameter = {
        "request": request,
        "queryset": queryset,
        "page_size": 10
    }

    data = Pagination(**parameter).get_content()

    # 添加form是为了使用它的表单备注来当前端数据的列头名
    form = PrettyNumModelForm()
    data['form'] = form
    data['keyword'] = keyword   # 临时加个搜索关键字看效果

    # labels = []
    # for field in form:
    #     labels.append(field.label)
    # print(labels)

    # 我忘了什么情况下发post请求了！，好像没用上，分页用的是href补地址
    if request.method == "POST":
        content = {
            "status": True,
            "keyword": keyword,
            "content": data
        }
        return JsonResponse(content)

    response = {
        "code": 200,
        "msg": "操作成功",
        "data": data
    }

    # pprint(response)

    # get请求返回响应
    return render(request, "mytest/pretty_list.html", response)


@csrf_exempt
def pretty_add(request):
    """ 缺陷添加 """

    return ComCrud().get_add(request, "PrettyNum")


def pretty_edit(request):
    """ 靓号编辑 """

    pass


@csrf_exempt
def pretty_delete(request):
    """ 靓号删除 """

    return ComCrud().get_delete(request, "PrettyNum")
